const Base = require('./base.js');
const svgCaptcha = require('think-svg-captcha');

module.exports = class extends Base {

	constructor(ctx) {
		super(ctx);
		this.user = this.model("system/user");
		this.rule = this.model("system/rule");
		this.unit = this.model("system/unit");
		this.role = this.model("system/role");
		this.log = this.model("system/log");
	}

	async loginAction() {
		

		if(this.isGet) {
			let auth = await this.session("auth");
			let user = await this.session("user") || {};
			if(auth && user.status == 1) {
				return this.redirect("/system/unit/index");
			}

			return this.display();
		} else {
			let posts = this.post();

			let username = posts.username;
			let password = posts.password;
			let captcha = posts.captcha;
			let captchaText = await this.session("captchaText") || '';
			let captchaMust = await this.session("captchaMust") || false;
			let errCount = await this.session("errorCount") || 0;
			if(!username || !password) {
				return this.fail("用户名密码不能为空");
			}
			if(captchaMust) { //验证验证码
				if(captcha == '') {
					return this.fail(1002, "请输入验证码");
				} else if(captchaText == captcha.toLowerCase()) {
					errCount = 0;
				} else {
					return this.fail("验证码不正确");
				}
			}
			if(errCount > 1) { //若输错密码三次则必须验证验证码
				await this.session("captchaMust", true);
				return this.fail(1002, "请输入验证码");
			}
			await this.session("errorCount", errCount + 1);

			let user = await this.user.where({
				username: username
			}).find();

			if(think.isEmpty(user)) {
				return this.fail("用户名不存在");
			}

			if(user.status == 0) {
				return this.fail("用户被禁止登录");
			}

			if(user.password != this.password(password, user.username, user.create_time)) {
				return this.fail("密码不正确");
			}
			if(user.is_admin != 1) {
				return this.fail("没有登录权限");
			}

			await this.user.setOne(user.id, {
				online: 1,
				last_login_ip: this.ip,
				last_login_time: new Date().valueOf(),
				login_count: user.login_count + 1
			});

			await this.log.add({
				type: 'system',
				url: this.ctx.url,
				note: "登录成功",
				user_id: user.id,
				create_nickname: user.nickname,
				create_ip: this.ip,
				create_time: new Date().valueOf()
			});

			let menus = await this.role.menusPermisson(user.role);

			await this.session("auth", true);
			await this.session("user", user);
			await this.session("captchaMust", false);
			await this.session("errorCount", 0);

			if(menus.roleIds.length == 0) {
				return this.success("登录成功");
			}
			let custom_menus = [];
			if(!think.isEmpty(user.custom_menus)){
				custom_menus = JSON.parse(user.custom_menus);
			}
			
			let customMenus = await this.rule.customMenus(custom_menus);

			await this.session("customMenus", customMenus);
			await this.session("firstMenus", menus.firstMenus);
			await this.session("secondMenus", menus.secondMenus);
			await this.session("permission", menus.permission);
			return this.success("登录成功");

		}

	}

	async captchaAction() {
		let captcha = new svgCaptcha();
		let data = captcha.create();
		await this.session("captchaText", data.text.toLowerCase());
		return this.ctx.res.end(data.data);

	}

	async logoutAction() {
		await this.session(null);
		return this.redirect("/system/user/login");

	}

	async indexAction() {

		if(this.isGet) {
			return this.display();
		}

		let posts = this.post();
		

		let unit_id = posts.unitid || 0;
		let username = posts.username;
		let nickname = posts.nickname;

		
		let where = {};
		if(unit_id > 0) {
			where.unit_id = unit_id;
		}
		if(!think.isEmpty(username)) {
			where.username = ['like', '%' + username + '%'];
		}
		if(!think.isEmpty(nickname)) {
			where.nickname = ['like', '%' + nickname + '%'];

		}
		const data = await this.user.dataTable(posts, where);
		return this.json(data);

	}

	async treeAction() {

		let pid = this.get("pid");

		let units = await this.unit.getChilds(pid);

		let data = [];
		if(!pid) {
			data = [{
				id: '0',
				text: '所有用户',
				children: 0
			}];

		}

		if(!think.isEmpty(units)) {

			units.forEach((o) => {
				let unit = {};
				unit.id = o.id;
				unit.text = o.name;
				unit.children = o.hasChildren == 1 ? true : false;
				data.push(unit);
			});

		}

		return this.json(data);

	}

	async addAction() {

		if(this.isGet) {
			return this.display();
		}

		let posts = this.post();

		let username = posts.username;
		let user = await this.user.where({
			username: username
		}).find();

		if(!think.isEmpty(user)) {
			return this.fail("用户名已存在");
		}

		let time = new Date().valueOf();

		let password = this.password(posts.password, username, time);

		let user_id = await this.user.add({
			username: posts.username,
			password: password,
			online: 0,
			status: 1,
			created_by: (await this.session("user")).id,
			create_time: time,
			unit_id: posts.unitid,
			nickname: posts.nickname,
			email: posts.email,
			mobile: posts.mobile

		});

		if(user_id == 0) {
			return this.fail("添加失败");
		}

		return this.success("添加成功");

	}

	

	async customAction() {

		if(this.isGet) {

			let user = await this.session("user");
			let menus = await this.role.menusPermisson(user.role);
			let customMenus = await this.session("customMenus") || [];
			this.assign("firstMenus", menus.firstMenus);
			this.assign("secondMenus", menus.secondMenus);
			this.assign("customMenus", JSON.stringify(customMenus));
			return this.display();

		}

		let posts = this.post();
		let user = await this.session("user");
		let rows = await this.user.setOne(user.id, {
			custom_menus: posts.ids
		});
		if(rows == 0) {
			return this.fail("保存失败");
		}

		let customMenus = await this.rule.customMenus(JSON.parse(posts.ids));

		user.customMenus = posts.ids;
		await this.session("user", user);
		await this.session("customMenus", customMenus);
		return this.success("保存成功");

	}

	async editAction() {
		if(this.isGet) {
			let userid = this.get("id");
			let user = await this.user.findOne(userid);
			if(!think.isEmpty(user)) {
				user.unit = await this.unit.findOne(user.unit_id);
			}
			this.assign("user", user);

			return this.display();
		}

		let posts = this.post();

		let oldusername = posts.oldusername;
		let username = posts.username;

		if(username != oldusername) {
			let user = await this.user.where({
				username: username
			}).find();
			if(!think.isEmpty(user)) {
				return this.fail("用户名已存在");
			}

		}

		let rows = await this.user.setOne(posts.id, {
			username: username,
			unit_id: posts.unitid,
			nickname: posts.nickname,
			email: posts.email,
			mobile: posts.mobile,
			update_time: new Date().valueOf()
		});
		if(rows == 0) {
			return this.fail("修改失败");
		}
		return this.success("修改成功");

	}

	async ruleAction() {

		let userid = this.get("id");
		let user = await this.user.findOne(userid);

		if(!think.isEmpty(user)) {

			let roleIds = [];
			let userRoles = user.role;
			userRoles.forEach((obj) => {
				roleIds.push(obj.id);

			});

			let permission = await this.role.permission(roleIds);

			console.log(permission);

			this.assign("userFirstMenus", permission.firstMenus);
			this.assign("userSecondMenus", JSON.stringify(permission.secondMenus));
			this.assign("user", user);
			return this.display();
		}

	}

	async passwordAction() {
		if(this.isGet) {

			return this.display();
		}

		let oldPassword = this.post("oldPassword");
		let newPassword = this.post("newPassword");
		let user = await this.session("user");
		let pass = this.password(oldPassword, user.username, user.create_time);

		if(pass != user.password) {
			return this.fail("密码不正确");
		}

		let newPass = this.password(newPassword, user.username, user.create_time);
		let rows = await this.user.setOne(user.id, {
			password: newPass
		});
		user.password = newPass;
		await this.session("user", user);

		if(rows == 0) {
			return this.fail("修改失败");
		}

		return this.success("修改成功");

	}
	async detailAction() {

		let userid = this.get("id");
		let user = await this.user.findOne(userid);

		if(!think.isEmpty(user)) {
			this.assign("user", user);
			return this.display();
		}

	}
	async resetpwdAction() {
		let id = this.post("id");

		let user = await this.user.findOne(id);
		let newpass = think.randomString(6);
		let password = this.password(newpass, user.username, user.create_time);
		let rows = 0;
		if(!think.isEmpty(user)) {
			rows = await this.user.setOne(id, {
				password: password
			});

		}
		if(rows == 0) {
			return this.fail("重置失败");
		}

		return this.success(newpass);

	}

	async layoutAction() {

		let posts = this.post();
		let user = await this.session("user");
		if('sidebar' == posts.p) {

			await this.user.setOne(user.id, {
				login_sidebar: posts.v
			});

		} else if('boxed' == posts.p) {

			await this.user.setOne(user.id, {
				login_boxed: posts.v
			});

		} else if('scroll' == posts.p) {
			await this.user.setOne(user.id, {
				login_scroll: posts.v
			});

		}
		let newUser = await this.user.findOne(user.id);
		await this.session("user", newUser);

		return this.success();

	}

	async themeAction() {

		let loginTheme = this.post("loginTheme");
		let user = await this.session("user");

		await this.user.setOne(user.id, {
			login_theme: loginTheme
		});
		let newUser = await this.user.findOne(user.id);
		await this.session("user", newUser);
		return this.success();

	}

};